package org.goodsmanager.controller;

import org.goodsmanager.entity.Address;
import org.goodsmanager.entity.User;
import org.goodsmanager.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 地址控制器
 */
@Controller
@RequestMapping("/address")
public class AddressController {
    
    @Autowired
    private AddressService addressService;
    
    /**
     * 地址列表页面
     */
    @GetMapping("/list")
    public String addressList(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        List<Address> addresses = addressService.getAddressesByUserId(Long.valueOf(user.getId()));
        model.addAttribute("addresses", addresses);
        
        return "shop/address-list";
    }
    
    /**
     * 添加地址
     */
    @PostMapping("/add")
    @ResponseBody
    public Map<String, Object> addAddress(
            @RequestParam String name,
            @RequestParam String phone,
            @RequestParam String province,
            @RequestParam String city,
            @RequestParam String district,
            @RequestParam String detail,
            @RequestParam(defaultValue = "false") boolean isDefault,
            HttpSession session) {
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            Address address = new Address();
            address.setUserId(Long.valueOf(user.getId()));
            address.setName(name);
            address.setPhone(phone);
            address.setProvince(province);
            address.setCity(city);
            address.setDistrict(district);
            address.setDetail(detail);
            address.setIsDefault(isDefault);
            
            boolean success = addressService.addAddress(address);
            
            if (success) {
                return Map.of("success", true, "message", "地址添加成功");
            } else {
                return Map.of("success", false, "message", "地址添加失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "地址添加失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新地址
     */
    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updateAddress(
            @RequestParam Long id,
            @RequestParam String name,
            @RequestParam String phone,
            @RequestParam String province,
            @RequestParam String city,
            @RequestParam String district,
            @RequestParam String detail,
            @RequestParam(defaultValue = "false") boolean isDefault,
            HttpSession session) {
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            // 检查地址是否属于当前用户
            Address address = addressService.getAddressById(id);
            if (address == null || !address.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "地址不存在");
            }
            
            address.setName(name);
            address.setPhone(phone);
            address.setProvince(province);
            address.setCity(city);
            address.setDistrict(district);
            address.setDetail(detail);
            address.setIsDefault(isDefault);
            
            boolean success = addressService.updateAddress(address);
            
            if (success) {
                return Map.of("success", true, "message", "地址更新成功");
            } else {
                return Map.of("success", false, "message", "地址更新失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "地址更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除地址
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Map<String, Object> deleteAddress(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            // 检查地址是否属于当前用户
            Address address = addressService.getAddressById(id);
            if (address == null || !address.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "地址不存在");
            }
            
            boolean success = addressService.deleteAddress(id);
            
            if (success) {
                return Map.of("success", true, "message", "地址删除成功");
            } else {
                return Map.of("success", false, "message", "地址删除失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "地址删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 设置默认地址
     */
    @PostMapping("/setDefault/{id}")
    @ResponseBody
    public Map<String, Object> setDefaultAddress(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            // 检查地址是否属于当前用户
            Address address = addressService.getAddressById(id);
            if (address == null || !address.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "地址不存在");
            }
            
            boolean success = addressService.setDefaultAddress(Long.valueOf(user.getId()), id);
            
            if (success) {
                return Map.of("success", true, "message", "默认地址设置成功");
            } else {
                return Map.of("success", false, "message", "默认地址设置失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "默认地址设置失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取地址详情
     */
    @GetMapping("/get/{id}")
    @ResponseBody
    public Map<String, Object> getAddress(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            Address address = addressService.getAddressById(id);
            if (address == null || !address.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "地址不存在");
            }
            
            return Map.of("success", true, "address", address);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "获取地址失败：" + e.getMessage());
        }
    }
}